import { defineStore } from 'pinia'
import { SET_TOKEN } from "@/utils/token";
import { reqLogin, reqLogout, reqUserInfoUrl } from "@/api/user/index.ts";
import { loginFromData, loginResponseData, userInfoResponseData } from "@/api/user/type";
import { RouteRecordRaw } from "vue-router";
import { hasPermiOr, hasRole } from "@/store/modules/auth";


export const useUserStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: 'userState',
  // state: 返回对象的函数
  state: () => ({
    // 登录token
    token: null,
    // 登录用户信息
    userInfo: {},
    hasUserInfo: false,
    hasMenuRouter: false,
    // 角色
    roles: localStorage.roles ? JSON.parse(localStorage.roles) : [],
    // 权限
    permissions: [],
  }),
  getters: {},
  // 可以同步 也可以异步
  actions: {
    /*用户登录方法,async三种状态*/
    async userLogin(data: loginFromData) {
      return new Promise(async (resolve, reject) => {
        await reqLogin(data)
          .then(response => {
            // 将token进行存储
            this.token = response.token as string
            SET_TOKEN(response.token as string)
            resolve(response); // 登录成功，返回结果
          })
          .catch(error => {
            reject(error); // 登录失败，返回错误
          });
      });

    /*  const result: loginResponseData = await reqLogin(data)
      /!*登录成功获取到token，失败则返回错误信息*!/
      if (result.code === 200) {
        /!*登录成功*!/
        /!*存储token*!/
        this.token = result.token as string
        /!*再将token存到本地*!/
        SET_TOKEN(result.token as string)
        /!*返回成功，进入主页*!/
        return 'ok'
      } else {
        /!*登录失败, 将错误信息进行返回*!/
        return Promise.reject(new Error(result.message))
      }*/
    },

    /*获取用户信息*/
    async getUserInfo() {
      const result: userInfoResponseData = await reqUserInfoUrl()
      /*获取到的信息存储到仓库当中*/
      console.log('User')
      console.log(result)
      if (result.code === 200) {
        /*获取成功*/
        console.log('获取用户信息成功')
        this.userInfo.avatar = result.user.avatar /*将结果赋值给userInfo*/
        this.userInfo.username = result.user.username /*将结果赋值给userInfo*/


        this.avatar = result.user.avatar
        this.username = result.user.username
        this.permissions = result.permissions

        /*角色信息*/
        this.roles = result.roles

        /*将用户信息存储到userInfo中*/
        this.userInfo = result.user
        this.hasUserInfo = true;/*获取成功*/
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    // 退出
    logout() {
      return new Promise(async (resolve, reject) => {
        // 登出
        await reqLogout().then((req) => {
          if(req.code === 200){
            this.hasUserInfo = false;
            this.token = null
            this.userInfo = {}
            this.roles = []
            resolve(null)
          }else {
            // 事变
            reject()
          }
        })
      })
    },



    /*动态获取路由信息*/
    async getRouter() {
      const result = await reqGetRouter()
      console.log('获取路由信息getRouter')
      console.log(result)
      if (result.code === 200) {
        this.hasMenuRouter = true
        /*将data存到menuList中*/
        //将原始数据进行深拷贝，防止修改原始数据
        const sdata = JSON.parse(JSON.stringify(result.data))
        const rdata = JSON.parse(JSON.stringify(result.data))

        /*生成需要添加的路由表的路由*/
        const lastRouterRouters =
          filterAsyncRouter(sdata) /*获取的是动态路由信息*/
        console.log('lastRouterRouters', lastRouterRouters)
        /*生成菜单中要使用的路由*/
        const lastRouterMenu = filterAsyncRouter(
          rdata,
          false,
          true,
        ) /*获取的数路由的菜单信息*/
        console.log('lastRouterMenu', lastRouterMenu)
        //对动态路由进行过滤
        const asyncRoutes = filterDynamicRoutes(asnycRouters)

        /*console.log('asyncRoutes', asyncRoutes)
        ;[...asyncRoutes].forEach((route) => {
          try {
            router.addRoute(route)
          } catch (e) {
            console.log(e)
          }
        })

        /!*添加动态路由*!/
        ;[...constantRouters, ...lastRouterRouters, ...anyRoutes].forEach(
          (route) => {
            try {
              router.addRoute(route)
            } catch (e) {
              console.log(e)
            }
          },
        )*/

        //设置路由表
        /*this.menuRoutes = constantRouters.concat(lastRouterMenu)*/



        //查看所有路由
        console.log('所有路由')
        //console.log(router.getRoutes())

        return lastRouterRouters
      } else {
        /*登录失败*/
        return Promise.reject(new Error(result.message))
      }
    },
  },
  // 进行持久化存储
  persist: {
    // 本地存储的名称
    key: 'userState',
    //保存的位置
    storage: window.localStorage, //localstorage
  },
})


const modules = import.meta.glob('../../views/**/*.vue') /*获取所有的.vue组件*/
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(
  asyncRouterMap: any[],
  lastRouter = false,
  type = false,
) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      /*对path的拼接*/
      route.children = filterChildren(route.children, route)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = () => import('@/layout/index.vue')
      } else if (route.component === 'ParentView') {
        route.component = () => import('@/components/ParentView/index.vue')
      } else if (route.component === 'InnerLink') {
        route.component = () =>
          import('@/layout/components/InnerLink/index.vue')
      } else {
        if (modules[`../../views/${route.component}.vue`] != null) {
          route.component = modules[`../../views/${route.component}.vue`]
        }
      }
    }
    /*该路由有孩子*/
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return route
  })
}

/*对孩子的path进行拼接*/
function filterChildren(
  childrenMap: any[],
  lastRouter = false,
): RouteRecordRaw[] {
  let children: any[] = [] /*用老记录孩子的路由信息，最后进行返回*/
  childrenMap.forEach((el, index: number) => {
    /*如果该元素有孩子并且孩子超过一个*/
    if (el.children && el.children.length) {
      /*该元素的commponent为ParentView没有lastRouter*/
      if (el.component === 'ParentView' && !lastRouter) {
        /*ParentView表示的是该组件的元素的位置*/
        /*遍历该元素的孩子的孩子，对其进行路由拼接*/
        el.children.forEach((c: any) => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes: any[]) {
  const res: any[] = []
  routes.forEach((route) => {
    console.log('-----------------------------0')
    console.log(route.permissions)
    if (route.permissions) {
      if (hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (hasRole(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

/*const loadView = (view: string) => () => import(`@/views/${view}.vue`)*/

export const loadView = (view: string) => {
  return () => import(`@/views/${view}.vue`)
  /*if (import.meta.env.DEV) {
            return () => import(`@/views/${view}.vue`)
        } else {
            // 使用 import 实现生产环境的路由懒加载
            return () => import(`@/views/${view}.vue`)
        }*/
}
